<template>
  <div class="vehicle-management">
    <h1>车辆管理</h1>
    
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="search-area">
            <el-input
              v-model="searchQuery"
              placeholder="搜索车辆（品牌/型号/状态）"
              class="search-input"
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><search /></el-icon>
              </template>
            </el-input>
          </div>
          
          <div>
            <el-button type="primary" @click="handleAddVehicle">
              <el-icon><plus /></el-icon> 添加车辆
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table
        :data="filteredVehicles"
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column label="车辆图片" width="100">          
          <template #default="scope">
            <el-image
              :src="getImageUrl(scope.row.imageUrl)"
              :preview-src-list="scope.row.imageUrl ? [getImageUrl(scope.row.imageUrl)] : []"
              fit="cover"
              style="width: 80px; height: 60px; border-radius: 4px;"
              @error="() => handleImageError($event)"
            />
          </template>        
        </el-table-column>
        <el-table-column prop="brand" label="品牌" width="100" />
        <el-table-column prop="model" label="型号" width="100" />
        <el-table-column prop="licensePlate" label="车牌号" width="100" />
        <el-table-column prop="dailyPrice" label="日租金" width="100">
          <template #default="scope">
            ¥{{ scope.row.dailyPrice }}
          </template>
        </el-table-column>
        <el-table-column prop="currentLocation" label="当前位置" width="150" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="所属车行" width="120">
          <template #default="scope">
            {{ getShopName(scope.row.shopId) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="240">
          <template #default="scope">
            <div style="display: flex; gap: 2px;">
              <el-button type="primary" size="small" @click="handleEdit(scope.row)">
                编辑
              </el-button>
              <el-button
                :type="scope.row.status === 1 ? 'warning' : 'success'"
                size="small"
                @click="handleStatusChange(scope.row)"
              >
                {{ scope.row.status === 1 ? '设为维护' : '设为可租' }}
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row.id)">
                删除
              </el-button>
            </div>
          </template>

        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 添加/编辑车辆对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑车辆信息' : '添加新车辆'"
      width="600px"
    >
      <el-form :model="vehicleForm" label-width="100px" :rules="rules" ref="vehicleFormRef">
        <el-form-item label="品牌" prop="brand">
          <el-select v-model="vehicleForm.brand" filterable allow-create placeholder="选择或输入品牌">
            <el-option
              v-for="brand in carBrands"
              :key="brand"
              :label="brand"
              :value="brand"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="型号" prop="model">
          <el-select v-model="vehicleForm.model" filterable allow-create placeholder="选择或输入型号">
            <el-option
              v-for="model in getModelsByBrand(vehicleForm.brand)"
              :key="model"
              :label="model"
              :value="model"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="车牌号" prop="licensePlate">          
          <el-input v-model="vehicleForm.licensePlate" placeholder="例：京A12345" />        
        </el-form-item>        
                      <el-form-item label="颜色" prop="color">          
                <el-select v-model="vehicleForm.color" filterable allow-create placeholder="选择或输入颜色">
                  <el-option
                    v-for="color in carColors"
                    :key="color.value"
                    :label="color.label"
                    :value="color.value">
                    <div style="display: flex; align-items: center;">
                      <span style="display: inline-block; width: 16px; height: 16px; background-color: #409eff; margin-right: 8px; border-radius: 2px;"
                        :style="{ backgroundColor: color.hex }"></span>
                      <span>{{ color.label }}</span>
                    </div>
                  </el-option>
                </el-select>       
              </el-form-item>                
        <el-form-item label="座位数" prop="seatCount">          
          <el-input-number v-model="vehicleForm.seatCount" :min="1" :max="20" />        
        </el-form-item>        
        <el-form-item label="日租金" prop="dailyPrice">          
          <el-input-number v-model="vehicleForm.dailyPrice" :min="1" :precision="2" :step="10" />        
        </el-form-item>
        <el-form-item label="当前位置" prop="currentLocation">          
          <div style="display: flex; align-items: center; gap: 10px;">            
            <el-input v-model="vehicleForm.currentLocation" placeholder="选择或输入位置" style="flex-grow: 1;" />            
            <el-button type="primary" @click="showLocationMap">选择位置</el-button>          
          </div>        
        </el-form-item>
        <el-form-item label="所属车行" prop="shopId">
          <el-select v-model="vehicleForm.shopId" placeholder="请选择车行">
            <el-option
              v-for="shop in shopList"
              :key="shop.id"
              :label="shop.shopName"
              :value="shop.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="车辆状态" prop="status">
          <el-select v-model="vehicleForm.status">
            <el-option :value="1" label="可租用" />
            <el-option :value="2" label="已租出" />
            <el-option :value="3" label="维护中" />
          </el-select>
        </el-form-item>
        <el-form-item label="车辆图片" prop="imageUrl">
          <el-upload
              class="vehicle-image-uploader"
              :auto-upload="false"
              :show-file-list="false"
              :before-upload="beforeImageUpload"
              :on-change="handleFileChange"
              ref="uploadRef"
          >
            <img v-if="vehicleForm.imageUrl" :src="getFormImageUrl(vehicleForm.imageUrl)" class="preview-image" />
            <div v-if="vehicleForm.imageUrl" class="preview-actions">
              <el-icon @click.stop="handleRemoveFile"><Delete /></el-icon>
            </div>
            <template v-if="!vehicleForm.imageUrl">
              <el-icon v-if="!isUploading" class="upload-icon"><Plus /></el-icon>
              <el-icon v-else class="upload-icon"><Loading /></el-icon>
              <div class="upload-tip">{{ isUploading ? '上传中...' : '点击上传车辆图片' }}</div>
            </template>
          </el-upload>
        <div v-if="vehicleForm.imageUrl" style="margin-top: 5px; display: flex; align-items: center;">
          <span style="font-size: 12px; color: #909399;">图片已上传</span>
          <el-button type="danger" size="small" @click="handleRemoveFile" style="margin-left: 10px;">清除</el-button>
        </div>
      </el-form-item>
        <el-form-item label="车辆描述" prop="description">
          <el-input type="textarea" v-model="vehicleForm.description" rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
              type="primary"
              :loading="isUploading"
              @click="submitVehicleForm"
          >
        {{ isUploading ? '上传中...' : '确认' }}
      </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="确认删除"
      width="300px"
    >
      <div class="delete-confirm">
        确定要删除该车辆吗？此操作不可恢复！
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确认删除</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 地图选择对话框 -->    
     <el-dialog      
     v-model="mapDialogVisible"      
     title="选择车辆位置"      
     width="700px"    
     >      
     <MapSelector         
     ref="mapSelectorRef"        
     :initialLocation="vehicleForm.currentLocation"        
     @locationConfirmed="handleLocationConfirmed"      
     />      
     <template #footer>        
      <span class="dialog-footer">          
        <el-button @click="mapDialogVisible = false">取消</el-button>          
        <el-button type="primary" @click="confirmSelectedLocation">确认位置</el-button>        
      </span>      
    </template>    
  </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed, watch } from 'vue'
import { Search, Plus, Delete, Loading } from '@element-plus/icons-vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { nextTick } from 'vue'
import MapSelector from '@/components/map/MapSelector.vue'

export default {
  name: 'VehicleManagement',
  components: {
    Search,
    Plus,
    Loading,
    Delete,
    MapSelector
  },
  setup() {
    const loading = ref(false)
    const vehicles = ref([])
    const searchQuery = ref('')
    const dialogVisible = ref(false)
    const deleteDialogVisible = ref(false)
    const isEdit = ref(false)
    const vehicleFormRef = ref(null)
    const deleteVehicleId = ref(null)
    const uploadingFile = ref(null)
    const isUploading = ref(false)
    const mapDialogVisible = ref(false)    
    const mapSelectorRef = ref(null)
    const shopList = ref([])
    
    // 文件上传请求头    
    const uploadHeaders = ref({      
      Authorization: `Bearer ${localStorage.getItem('token') || ''}`    
    })
    
    // 表单数据    
    const vehicleForm = ref({      
      brand: '',      
      model: '',      
      licensePlate: '', // 前端用licensePlate，提交时转换为plateNumber      
      color: '',      
      seatCount: 5,      
      dailyPrice: 100,      
      currentLocation: '',      
      shopId: 1,      
      status: 1,      
      imageUrl: '',      
      description: ''    
    })
    
    // 表单验证规则    
    const rules = {      
      brand: [{ required: true, message: '请输入品牌', trigger: 'blur' }],      
      model: [{ required: true, message: '请输入型号', trigger: 'blur' }],      
      licensePlate: [{ required: true, message: '请输入车牌号', trigger: 'blur' }],      
      color: [{ required: true, message: '请输入颜色', trigger: 'blur' }],      
      seatCount: [{ required: true, message: '请输入座位数', trigger: 'blur' }],      
      dailyPrice: [{ required: true, message: '请输入日租金', trigger: 'blur' }],      
      currentLocation: [{ required: true, message: '请输入当前位置', trigger: 'blur' }],      
      shopId: [{ required: true, message: '请选择所属车行', trigger: 'blur' }],      
      status: [{ required: true, message: '请选择车辆状态', trigger: 'blur' }]    
    }
    
    const filteredVehicles = computed(() => {
      if (!searchQuery.value) {
        return vehicles.value
      }
      const query = searchQuery.value.toLowerCase()
      return vehicles.value.filter(vehicle => 
        vehicle.brand.toLowerCase().includes(query) ||
        vehicle.model.toLowerCase().includes(query) ||
        getStatusText(vehicle.status).includes(query)
      )
    })
    
    const fetchVehicles = async () => {
      loading.value = true
      try {
        console.log('正在获取车辆列表...')
        // 尝试从后端管理API获取
        let res
        try {
          res = await axios.get('/api/admin/vehicles')
          console.log('从管理API获取车辆列表成功:', res)
        } catch (adminApiError) {
          console.log('从管理API获取失败，尝试普通API:', adminApiError)
          // 如果管理API失败，尝试普通API
          res = await axios.get('/api/vehicle/list')
          console.log('从普通API获取车辆列表成功:', res)
        }
        
        if (res.data.success) {
          // 处理不同的响应结构
          if (res.data.data.records) {
            // 分页结构
            vehicles.value = res.data.data.records || []
          } else if (Array.isArray(res.data.data)) {
            // 直接数组结构
            vehicles.value = res.data.data
          } else {
            vehicles.value = []
          }
          console.log('车辆列表数据已加载:', vehicles.value)
        } else {
          throw new Error(res.data.message || '获取车辆列表失败')
        }
      } catch (error) {
        console.error('获取车辆列表失败:', error)
        ElMessage.error(error.message || '获取车辆列表失败')
      } finally {
        loading.value = false
      }
    }
    
         const fetchShops = async () => {
       try {
         console.log('正在获取车行列表...')
         // 先尝试从管理API获取
         let res
         try {
           res = await axios.get('/api/admin/shops')
           console.log('从管理API获取车行列表成功:', res)
         } catch (adminApiError) {
           console.log('从管理API获取失败，使用默认数据:', adminApiError)
           // 如果API失败，使用一些默认数据
           shopList.value = [
             { id: 1, shopName: '北京朝阳租车行' },
             { id: 2, shopName: '上海浦东租车中心' },
             { id: 3, shopName: '广州白云汽车租赁' },
             { id: 4, shopName: '深圳南山租车行' },
             { id: 5, shopName: '成都武侯租车点' }
           ]
           console.log('已加载默认车行列表:', shopList.value)
           return
         }
         
         if (res.data.success) {
           shopList.value = res.data.data || []
           console.log('获取到车行列表:', shopList.value)
         } else {
           throw new Error(res.data.message || '获取车行列表失败')
         }
       } catch (error) {
         console.error('获取车行列表失败:', error)
         ElMessage.error(error.message || '获取车行列表失败')
         // 如果完全失败，至少提供一些默认数据
         shopList.value = [
           { id: 1, shopName: '默认车行-北京' },
           { id: 2, shopName: '默认车行-上海' },
           { id: 3, shopName: '默认车行-广州' }
         ]
       }
     }
    
    const getStatusType = (status) => {
      switch (status) {
        case 1: return 'success'  // 可租用
        case 2: return 'warning'  // 已租出
        case 3: return 'info'     // 维护中
        default: return 'info'
      }
    }
    
    const getStatusText = (status) => {
      switch (status) {
        case 1: return '可租用'
        case 2: return '已租出'
        case 3: return '维护中'
        default: return '未知'
      }
    }
    
    const handleSearch = () => {
      // 搜索功能通过computed属性filteredVehicles自动实现
    }
    
    const handleAddVehicle = () => {
      console.log('添加车辆按钮被点击')
      isEdit.value = false      
      vehicleForm.value = {        
        brand: '',        
        model: '',        
        licensePlate: '',  // 注意：这里应该与后端字段匹配
        color: '',        
        seatCount: 5,        
        dailyPrice: 100,        
        currentLocation: '',        
        shopId: shopList.value.length > 0 ? shopList.value[0].id : 1,        
        status: 1,        
        imageUrl: '',        
        description: ''      
      }
      // 新增重置验证
      nextTick(() => {
        if (vehicleFormRef.value) {
          vehicleFormRef.value.resetFields()
        }
        console.log('对话框将显示')
        dialogVisible.value = true
        console.log('对话框显示状态:', dialogVisible.value)
      })
    }
    
    const handleEdit = (row) => {
      isEdit.value = true
      // 创建一个副本，并添加正确的licensePlate字段
      const rowWithLicensePlate = { 
        ...row,
        licensePlate: row.plateNumber || '' // 从plateNumber复制到licensePlate字段
      }
      vehicleForm.value = rowWithLicensePlate
      
      // 确保URL能正确显示
      if (vehicleForm.value.imageUrl) {
        console.log('编辑车辆，图片URL:', vehicleForm.value.imageUrl)
      }
      
      // 确保车型选项正确加载
      if (vehicleForm.value.brand && !carModels.value[vehicleForm.value.brand]) {
        // 如果品牌不在预定义列表中，将其添加到carModels
        carModels.value[vehicleForm.value.brand] = [vehicleForm.value.model]
        console.log(`添加自定义品牌: ${vehicleForm.value.brand}，型号: ${vehicleForm.value.model}`)
      }
      
      dialogVisible.value = true
    } 

    const submitVehicleForm = async () => {
      // 先验证表单
      if (!vehicleFormRef.value) return
      const valid = await vehicleFormRef.value.validate()
      if (!valid) return

      isUploading.value = true

      try {
        // 打印检查数据
        console.log('提交的表单数据:', vehicleForm.value)
        
        // 1. 先提交车辆数据（不包含可能超长的临时图片URL）
        // 确保字段名与后端匹配
        const vehicleData = {
          brand: vehicleForm.value.brand,
          model: vehicleForm.value.model,
          plateNumber: vehicleForm.value.licensePlate, // 转换为后端字段名
          color: vehicleForm.value.color,
          seatCount: vehicleForm.value.seatCount || 5,
          dailyPrice: vehicleForm.value.dailyPrice || 100,
          currentLocation: vehicleForm.value.currentLocation,
          shopId: vehicleForm.value.shopId || 1,
          status: vehicleForm.value.status || 1,
          description: vehicleForm.value.description || ''
        }
        
        // 如果是编辑，添加ID
        if (isEdit.value && vehicleForm.value.id) {
          vehicleData.id = vehicleForm.value.id
        }
        
        // 打印检查后端数据格式
        console.log('发送到后端的数据:', vehicleData)
        
        let vehicleRes
        if (isEdit.value) {
          // 使用车辆更新接口 - 使用POST而不是PUT
          vehicleRes = await axios.post(`/api/vehicle/${vehicleForm.value.id}`, vehicleData)
        } else {
          // 使用车辆添加接口
          vehicleRes = await axios.post('/api/vehicle/add', vehicleData)
        }

        console.log('后端响应:', vehicleRes.data)

        if (!vehicleRes.data.success) {
          throw new Error(vehicleRes.data.message || '操作失败')
        }

        // 2. 获取车辆ID（新增时）
        const vehicleId = isEdit.value ? vehicleForm.value.id : vehicleRes.data.data

        // 3. 上传图片（如果有）
        if (uploadingFile.value) {
          const formData = new FormData()
          formData.append('file', uploadingFile.value)
          formData.append('vehicleId', vehicleId)

          console.log('上传图片，车辆ID:', vehicleId)

          const uploadRes = await axios.post('/api/admin/upload/vehicleImage', formData, {
            headers: {
              'Content-Type': 'multipart/form-data',
              'Authorization': `Bearer ${localStorage.getItem('token') || ''}`
            }
          })

          console.log('图片上传响应:', uploadRes.data)

          if (uploadRes.data.success) {
            // 从后端接口返回的图片URL更新车辆
            const imageUrl = uploadRes.data.data.url
            
            console.log('更新图片URL:', imageUrl)
            
            // 4. 更新车辆图片URL到数据库 - 由UploadController处理
            // 这里不再需要单独更新imageUrl
          } else {
            throw new Error(uploadRes.data.message || '图片上传失败')
          }
        }

        // 释放临时URL
        if (vehicleForm.value.imageUrl && vehicleForm.value.imageUrl.startsWith('blob:')) {
          URL.revokeObjectURL(vehicleForm.value.imageUrl)
        }

        ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
        dialogVisible.value = false
        await fetchVehicles()
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error(error.message || '操作失败')
      } finally {
        isUploading.value = false
        uploadingFile.value = null
      }
    };
    
    const handleStatusChange = async (row) => {
      // 切换车辆状态：如果是可租状态，切换为维护状态；如果不是可租状态，切换为可租状态
      const newStatus = row.status === 1 ? 3 : 1
      try {
        // 使用最新的车辆更新接口
        const res = await axios.post(`/api/vehicle/${row.id}`, {
          id: row.id,
          status: newStatus,
          lastMaintenanceTime: newStatus === 3 ? new Date().toISOString() : null
        });
        if (res.data.success) {
          ElMessage.success(`车辆状态已更新为${getStatusText(newStatus)}`)
          fetchVehicles()
        } else {
          ElMessage.error(res.data.message || '操作失败')
        }
      } catch (error) {
        console.error('更改车辆状态失败:', error)
        ElMessage.error('更改车辆状态失败')
      }
    }
    
    const handleDelete = (id) => {      
      deleteVehicleId.value = id      
      deleteDialogVisible.value = true    
    }       
    // 图片上传前的验证
    const beforeImageUpload = (file) => {
      const validTypes = ['image/jpeg', 'image/png', 'image/webp'];
      const isImage = validTypes.includes(file.type);
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isImage) {
        ElMessage.error('仅支持 JPG/PNG/WEBP 格式!');
        return false;
      }
      if (!isLt5M) {
        ElMessage.error('图片大小不能超过5MB!');
        return false;
      }

      // 存储文件对象用于后续上传
      uploadingFile.value = file;
      return false; // 关闭自动上传
    };

    const handleUploadRequest = async (options) => {
      try {
        const formData = new FormData();
        formData.append('file', options.file);
        if (vehicleForm.value.id) {
          formData.append('vehicleId', vehicleForm.value.id);
        }

        const res = await axios.post(options.action, formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
            'Authorization': uploadHeaders.Authorization
          }
        });

        if (res.data.code === 200) {
          options.onSuccess(res.data); // 手动触发成功回调
        } else {
          options.onError(new Error(res.data.message));
        }
      } catch (error) {
        options.onError(error);
      }
    };
    const uploadRef = ref(null)

    // 清理上传状态
    const handleRemoveFile = () => {
      // 如果存在临时URL，需要释放它
      if (vehicleForm.value.imageUrl && vehicleForm.value.imageUrl.startsWith('blob:')) {
        URL.revokeObjectURL(vehicleForm.value.imageUrl)
      }
      vehicleForm.value.imageUrl = '';
      uploadingFile.value = null;
      // 清空上传组件内部文件列表
      if (uploadRef.value) {
        uploadRef.value.clearFiles();
      }
    };

        // 图片上传成功的回调 - 实际项目中使用这个，现在我们用base64简化          
    const handleImageUploadSuccess = (res) => {
      if (res.code === 200 && res.data) {
        vehicleForm.value.imageUrl = res.data.url;
        ElMessage.success('图片上传成功');
      } else {
        ElMessage.error(res.message || '图片上传失败');
      }
      isUploading.value = false; // 确保上传状态重置
    };

    const handleFileChange = (file) => {
      if (!file || !file.raw) {
        ElMessage.error('文件选择失败')
        return
      }

      // 如果已有临时URL，先释放它
      if (vehicleForm.value.imageUrl && vehicleForm.value.imageUrl.startsWith('blob:')) {
        URL.revokeObjectURL(vehicleForm.value.imageUrl)
      }

      // 存储文件对象用于后续提交时上传
      uploadingFile.value = file.raw
      
      // 仅创建临时URL用于预览，不使用Base64（会导致数据库字段超长）
      const tempUrl = URL.createObjectURL(file.raw)
      vehicleForm.value.imageUrl = tempUrl
      
      console.log('临时图片预览:', tempUrl)
    }

    const handleUploadError = (error) => {
      ElMessage.error(`图片上传失败: ${error.message}`);
      isUploading.value = false;
    };
    
    const confirmDelete = async () => {
      if (!deleteVehicleId.value) return
      
      try {
        // 使用正确的删除接口
        const res = await axios.delete(`/api/vehicle/${deleteVehicleId.value}`)
        if (res.data.success) {
          ElMessage.success('车辆已删除')
          fetchVehicles()
          deleteDialogVisible.value = false
        } else {
          ElMessage.error(res.data.message || '删除失败')
        }
      } catch (error) {
        console.error('删除车辆失败:', error)
        ElMessage.error('删除车辆失败')
      }
    }
    
    const getImageUrl = (url) => {
      if (!url) return '/assets/no-image.png';
      
      // 如果是绝对URL（以http开头），直接返回
      if (url.startsWith('http://') || url.startsWith('https://')) {
        // 如果是placeholder站点且有连接问题，使用本地占位图
        if (url.includes('via.placeholder.com')) {
          return '/assets/no-image.png';
        }
        return url;
      }
      
      // 如果是相对URL，需要检查格式并调整
      
      // 1. 修正端口问题：从3000改为8081
      if (url.includes('localhost:3000')) {
        url = url.replace('localhost:3000', 'localhost:8081');
      }
      
      // 2. 如果URL不以/开头，添加/
      if (!url.startsWith('/')) {
        url = '/' + url;
      }
      
      // 拼接服务器地址，使用正确的端口8081
      const host = window.location.protocol + '//' + window.location.hostname + ':8081';
      return host + url;
    }
    
    const handleImageError = (e) => {
      if (e && e.target) {
        // 使用本地资源文件夹中的占位图
        e.target.src = '/assets/no-image.png';
      }
    }
    
    const getFormImageUrl = (url) => {
      if (!url) return '';
      
      // 如果是Blob URL（本地预览）
      if (url.startsWith('blob:')) {
        return url;
      }
      
      // 否则使用与列表相同的URL处理逻辑
      return getImageUrl(url);
    }

    // 显示地图选择器    
    const showLocationMap = () => {      
      mapDialogVisible.value = true;    
    }        
    // 确认地图选择的位置    
    const confirmSelectedLocation = () => {      
      if (mapSelectorRef.value) {        
        mapSelectorRef.value.confirmLocation();      
      }    
    }        
    // 位置确认回调    
    const handleLocationConfirmed = (location) => {      
      vehicleForm.value.currentLocation = location;      
      mapDialogVisible.value = false;      
      ElMessage.success('位置已设置');    
    }
    
    // 获取车行名称
    const getShopName = (shopId) => {
      const shop = shopList.value.find(shop => shop.id === shopId)
      return shop ? shop.shopName : `车行ID: ${shopId}`
    }
    
    // 预定义的汽车品牌和型号
         const carBrands = ref([
       '大众', '丰田', '本田', '福特', '奥迪', '宝马', '奔驰', '雪佛兰', '日产', '现代',
       '起亚', '标致', '雪铁龙', '沃尔沃', '特斯拉', '比亚迪', '吉利', '长安', '五菱', '一汽'
     ])
     
     // 预定义的汽车颜色
     const carColors = ref([
       { value: '黑色', label: '黑色', hex: '#000000' },
       { value: '白色', label: '白色', hex: '#ffffff' },
       { value: '银色', label: '银色', hex: '#C0C0C0' },
       { value: '灰色', label: '灰色', hex: '#808080' },
       { value: '红色', label: '红色', hex: '#FF0000' },
       { value: '蓝色', label: '蓝色', hex: '#0000FF' },
       { value: '绿色', label: '绿色', hex: '#008000' },
       { value: '棕色', label: '棕色', hex: '#A52A2A' },
       { value: '金色', label: '金色', hex: '#FFD700' },
       { value: '橙色', label: '橙色', hex: '#FFA500' },
       { value: '紫色', label: '紫色', hex: '#800080' },
       { value: '珍珠白', label: '珍珠白', hex: '#FDFEFE' },
       { value: '深灰', label: '深灰', hex: '#A9A9A9' },
       { value: '香槟色', label: '香槟色', hex: '#F7E7CE' },
       { value: '黄色', label: '黄色', hex: '#FFFF00' }
     ])
    
    const carModels = ref({
      '大众': ['帕萨特', '迈腾', '途观', '途安', '高尔夫', '宝来', '速腾'],
      '丰田': ['凯美瑞', '卡罗拉', '汉兰达', '雅力士', 'RAV4', '普拉多', '兰德酷路泽'],
      '本田': ['雅阁', '思域', 'CR-V', '飞度', '奥德赛', '思铂睿'],
      '福特': ['福克斯', '蒙迪欧', '锐界', '翼虎', '翼搏', 'F-150'],
      '奥迪': ['A4L', 'A6L', 'Q5', 'Q7', 'A3', 'A8', 'TT'],
      '宝马': ['3系', '5系', 'X3', 'X5', '7系', 'i3', 'i8'],
      '奔驰': ['C级', 'E级', 'S级', 'GLC', 'GLE', 'GLA', 'A级'],
      '雪佛兰': ['迈锐宝', '科鲁兹', '科沃兹', '探界者', '创酷'],
      '日产': ['轩逸', '天籁', '奇骏', '逍客', '楼兰', 'GTR'],
      '现代': ['索纳塔', '伊兰特', '途胜', '圣达菲', 'ix35']
    })
    
    // 根据选择的品牌获取对应的型号列表
    const getModelsByBrand = (brand) => {
      return carModels.value[brand] || []
    }
    
    // 监听品牌变化，自动清空型号
    watch(() => vehicleForm.value.brand, (newBrand) => {
      if (newBrand && !carModels.value[newBrand]?.includes(vehicleForm.value.model)) {
        vehicleForm.value.model = ''
      }
    })
    
    onMounted(() => {
      fetchVehicles()
      fetchShops()
      // 确保鉴权头信息是最新的
      uploadHeaders.value = {
        Authorization: `Bearer ${localStorage.getItem('token') || ''}`
      }
    })
    
    return {
      loading,
      vehicles,
      filteredVehicles,
      searchQuery,
      dialogVisible,
      deleteDialogVisible,
      isEdit,
      vehicleForm,
      vehicleFormRef,
      rules,
      handleSearch,
      handleAddVehicle,
      handleEdit,
      handleStatusChange,
      handleDelete,
      submitVehicleForm,
      confirmDelete,
      getStatusType,
      getStatusText,
      beforeImageUpload,      
      handleImageUploadSuccess,
      uploadHeaders,
      handleFileChange,
      handleUploadRequest,
      uploadRef,
      isUploading,
      handleRemoveFile,
      getImageUrl,
      getFormImageUrl,
      handleImageError,
      // Map related      
      mapDialogVisible,      
      mapSelectorRef,      
      showLocationMap,      
      confirmSelectedLocation,      
      handleLocationConfirmed,
      // Shop related
      shopList,
             getShopName,
       // Car brand and model predefined data
       carBrands,
       getModelsByBrand,
       carColors
    }
  }
}
</script>

<style scoped>
.vehicle-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-input {
  width: 300px;
}

.delete-confirm {
  text-align: center;
  margin: 20px 0;
}

.vehicle-image-uploader {  
  display: flex;  
  justify-content: center;  
  align-items: center;  
  flex-direction: column;  
  border: 1px dashed #d9d9d9;  
  border-radius: 6px;  
  cursor: pointer;  
  position: relative;  
  overflow: hidden;  
  width: 200px; 
  height: 150px;
}
  
.vehicle-image-uploader:hover {  
  border-color: #409eff;
}
    
.preview-image {  
  width: 100%;  
  height: 100%;  
  object-fit: cover;
}
    
.upload-icon {
  font-size: 28px;
  color: #8c939d;
  width: 28px;
  height: 28px;
}
    
.upload-tip {
  margin-top: 10px;
  color: #909399;
  font-size: 12px;
}

.preview-actions {
  position: absolute;
  top: 5px;
  right: 5px;
  cursor: pointer;
  background: rgba(0,0,0,0.5);
  padding: 3px;
  border-radius: 50%;
}
</style> 